<template>
	<view class="h-fill">
		<u-navbar title="收支明细" titleColor="#fff" backIconColor="#fff" :background="navBg"></u-navbar>
		<uni-list v-if="list.length">
			<uni-list-item v-for="item in list" :title="item.note" :note="item.createTime" :key="item.id" :showArrow="false">
				<template v-slot:right="">
					<view class="uni-flex uni-column align-right">
						<text class="uni-text-normal" :style="{color: item.type === 1 ? '#D61719' : '#8BC24C'}">{{item.priceText}} 元</text>
						<text class="uni-text-gray uni-text-small">余额：{{item.balance}} 元</text>
					</view>
				</template>
			</uni-list-item>
			<uni-load-more :status="loadingStatus"></uni-load-more>
		</uni-list>
		<u-empty v-else></u-empty>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				list: [],
				loadingStatus: "noMore",
				page: 0,
				navBg: {
					'background-image': 'linear-gradient(to right, #434AD8, #8E77F5)'
				}
			}
		},
		onLoad() {
			this.reload();
		},
		async onPullDownRefresh() {
			await this.reload();
			uni.stopPullDownRefresh();
		},
		onReachBottom() {
			this.loadMore();
		},
		methods: {
			async reload() {
				if (this.loadingStatus === "loading") {
					return;
				}
				this.loadingStatus = "more";
				this.list = [];
				this.page = 0;
				await this.loadMore();
			},
			async loadMore() {
				if (this.loadingStatus === "loading" || this.loadingStatus === "noMore") {
					return;
				}
				let params = {
					pageNum: this.page + 1,
					pageSize: 20,
				}
				let prevStatus = this.loadingStatus;
				this.loadingStatus = "loading";
				try{
					let res = await this.$http.getBalanceDetail(params);
					if (res.records.length) {
						this.page += 1;
						res.records.forEach(item => {
							if (item.type === 1) {
								item.priceText = `+${item.price}`;
							} else {
								item.priceText = `-${item.price}`;
							}
						});
						this.list = this.list.concat(res.records);
					}
					if (res.total > this.list.length) {
						this.loadingStatus = "more";
					} else {
						this.loadingStatus = "noMore";
					}
				}catch(e){
					this.$log("加载收支明细遇到错误", e);
					this.loadingStatus = prevStatus;
				}
			}
		}
	}
</script>

<style>
	page {
		background-color: #FFFFFF;
	}
</style>
